package org.example;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.example.model.student.Gender;
import org.example.model.student.Student;
import org.example.model.weather.JsonRootBean;
import org.example.ws.HelloService;
//import org.example.ws.ServerShutdown;

import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Load client from here
 * @author Alex
 */
public class Main {
	private static String helpStr;
	static {
		readHelpStr();
	}
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		while (true){
			print_help();
			int choice = scanner.nextInt();
			switch (choice){
				case 1:getStudentById();break;
				case 2:getAllStudents();break;
				case 3:deleteStudentById();break;
				case 4:addStudent();break;
				case 5:print_help();break;
				case 6:getWeather();break;
				case 7:helloService();break;
//				case 8:shutdownServer();break;
				case 0:return;
				default:
					System.out.println("Error!");
			}
		}
	}
	private static void print_help() {
		System.out.println(helpStr);
	}
	
	private static void readHelpStr() {
		File file = new File("Client/src/main/resources/help_EN.txt");
		FileReader fr=null;
		if (file.exists()){
			try {
				fr = new FileReader(file);
			} catch (FileNotFoundException e) {
				throw new RuntimeException(e);
			}
		}else {
			readJar();
			return;
		}
		
		char[] buffer = new char[1024];
		int count;
		try {
			while ((count=fr.read(buffer))!=-1){
//				System.out.println(count);
				helpStr = new String(buffer, 0, count);
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		if (fr!=null) {
			try {
				fr.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	private static void readJar() {
		String path = "Client.jar";
		JarFile zf = null;
		try {
			zf = new JarFile(path);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		InputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(path));
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
		Charset charset = Charset.forName("UTF-8");
		ZipInputStream zin = new ZipInputStream(in,charset);
		ZipEntry ze;
		try {
			while((ze = zin.getNextEntry()) != null){
				if(ze.toString().equals("help_EN.txt")){
					BufferedReader br = new BufferedReader(
							new InputStreamReader(zf.getInputStream(ze)));
					String line;
					StringBuilder sb=new StringBuilder();
					while((line = br.readLine()) != null){
//						System.out.println(line.toString());
						sb.append(line).append("\n");
//						helpStr +=line+"\n";
					}
					helpStr=sb.toString();
					br.close();
					zin.closeEntry();
					return;
				}
//				System.out.println();
			}
			
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * pause the program until you enter any String
	 */
	private static void pause(){
		System.out.println("Please press any key to continue");
		Scanner scanner=new Scanner(System.in);
		scanner.next();
	}
	private static void getStudentById() {
		System.out.println("Please enter the student ID:");
		Scanner scanner=new Scanner(System.in);
		String id = scanner.next();
		Student student = WebClient
				.create("http://localhost:8080/Student/GetByID/"+id)
				.accept(MediaType.APPLICATION_JSON).
				get(Student.class);
		System.out.println(student);
		pause();
	}
	private static void getAllStudents() {
		List<Student> students = WebClient
				.create("http://localhost:8080/Student/GetAll")
				.accept(MediaType.APPLICATION_JSON)
				.get(new GenericType<List<Student>>(){});
		for (Student student:students){
			System.out.println(student);
		}
		pause();
	}
	private static void deleteStudentById() {
		System.out.println("Please enter the student ID:");
		Scanner scanner=new Scanner(System.in);
		String id = scanner.next();
		WebClient.create("http://localhost:8080/Student/GetByID/"+id).delete();
		System.out.println("Delete successfully!");
		pause();
	}
	private static void addStudent() {
		System.out.println("Please enter the student ID:");
		Scanner scanner=new Scanner(System.in);
		String id = scanner.next();
		System.out.println("Please enter the Chinese name:");
		String nameCN = scanner.next();
		System.out.println("Please enter the French name:");
		String nameFR = scanner.next();
		System.out.println("Please enter the class:");
		String classNum = scanner.next();
		System.out.println("Please enter the gender (F/M):");
		String gender = scanner.next();
		gender=gender.substring(0,1).toUpperCase();
		Student student = new Student(id, nameCN, nameFR, classNum, Gender.valueOf(gender));
		WebClient
				.create("http://localhost:8080/Student")
				.type(MediaType.APPLICATION_JSON)
				.post(student);
		System.out.println("Add Successfully!");
		pause();
	}
	
	private static void getWeather(){
		System.out.println("Please select the name of the city.");
		System.out.println("1.Paris");
		System.out.println("2.Hangzhou");
		System.out.println("0.Others");
		Scanner scanner=new Scanner(System.in);
		int choice = scanner.nextInt();
		String []cityNames={null,"paris","hangzhou"};
		String cityName=null;
		try {
			cityName = cityNames[choice];
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("The number you have entered is incorrect.");
		}
		if (cityName==null){
			System.out.println("Please enter the English name of the city:");
			cityName=scanner.next();
			cityName=cityName.toLowerCase();
		}
		System.out.println("Fetching the data from RapidAPI, please wait...");
		
		OkHttpClient client = new OkHttpClient();
		Request request = new Request.Builder()
				.url("https://weatherapi-com.p.rapidapi.com/current.json?q="+cityName)
				.get()
				.addHeader("X-RapidAPI-Key", "8a36437e8fmsh2a3b425070bba28p19a1ccjsn292ba7bf33f0")
				.addHeader("X-RapidAPI-Host", "weatherapi-com.p.rapidapi.com")
				.build();
		Response response=null;
		String json=null;
		try {
			response = client.newCall(request).execute();
			json=response.body().string();
//			System.out.println(json);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		Gson gson = new GsonBuilder()
				.setDateFormat("yyyy-MM-dd HH:mm")
				.create();
		
		JsonRootBean jsonRootBean = gson.fromJson(json, JsonRootBean.class);
		Date date = jsonRootBean.getLocation().getLocaltime();
		Locale.setDefault(new Locale("en", "US"));
		System.out.printf("Updating time：%s\n",new SimpleDateFormat("dd MMM yyyy HH:mm:ss").format(date));
		System.out.printf("Temperature：%s ℃\n",jsonRootBean.getCurrent().getTemp_c());
		System.out.printf("Wind speed: %s km/h\n",jsonRootBean.getCurrent().getWind_kph());
		System.out.printf("Wind direction: %s\n",jsonRootBean.getCurrent().getWind_dir());
		System.out.printf("Rainfall: %s mm\n",jsonRootBean.getCurrent().getPrecip_mm());
		System.out.printf("Humidity: %s\n",jsonRootBean.getCurrent().getHumidity());
		System.out.printf("Cloud Volume: \n",jsonRootBean.getCurrent().getCloud());
		System.out.printf("Visibility: %skm\n",jsonRootBean.getCurrent().getVis_km());
		pause();
	}
	private static void helloService(){
		System.out.println("Please enter your name：");
		Scanner scanner = new Scanner(System.in);
		String name = scanner.next();
		
		JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
		//设置原创访问的地址
		factory.setAddress("http://localhost:8000/ws/hello");
		//设置接口类型
		factory.setServiceClass(HelloService.class);
		//对 接口 生产 代理 对象
		HelloService helloService = factory.create(HelloService.class);
//		System.out.println(helloService.getClass());
		String content = helloService.hello(name);
		System.out.println(content);
		pause();
	}
	
	/**
	 * This method has not been implemented yet,Please DO NOT call it.
	 */
	private static void shutdownServer(){
		/*JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
		//设置原创访问的地址
		factory.setAddress("http://localhost:8000/ws/st");
		//设置接口类型
		factory.setServiceClass(ServerShutdown.class);
		//对 接口 生产 代理 对象
		ServerShutdown helloService = factory.create(ServerShutdown.class);
//		System.out.println(helloService.getClass());
		helloService.shutdown();
		pause();*/
	}
}
